package com.yh.csx.crm.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yh.b2b.common.constant.ResponseCode;
import com.yh.b2b.common.response.CommonResultResponse;
import com.yh.b2b.common.util.HotFileUtils;
import com.yh.b2b.storagecenter.facade.stub.LocationInfoFacade;
import com.yh.b2b.storagecenter.facade.stub.vo.response.ResSimpleLocationInfoVO;
import com.yh.csx.crm.core.enums.CreditLevelDimensionEnum;
import com.yh.csx.crm.core.enums.PositionEnum;
import com.yh.csx.crm.core.enums.UploadFileSuffixEnum;
import com.yh.csx.crm.core.enums.UserTypeEnum;
import com.yh.csx.crm.core.exception.BusinessException;
import com.yh.csx.crm.service.request.BankNumberReq;
import com.yh.csx.crm.service.request.CreditLevelReq;
import com.yh.csx.crm.service.request.UploadFile;
import com.yh.csx.crm.core.util.BeanUtils;
import com.yh.csx.crm.dao.*;
import com.yh.csx.crm.po.*;
import com.yh.csx.crm.service.response.BankNumberResp;
import com.yh.csx.crm.service.response.CreditLevelItemResp;
import com.yh.csx.crm.service.response.CreditLevelResultResp;
import com.yh.csx.crm.service.response.ShopLocationResp;
import com.yh.csx.crm.service.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * PublicService class
 *
 * @author huyalin
 * @date 2019/2/22
 */
@Service
public class PublicService {

    @Autowired
    SysCompanyCodeMapper sysCompanyCodeMapper;

    @Autowired
    SysCustomerCategoryMapper sysCustomerCategoryMapper;

    @Autowired
    SysRegionMapper sysRegionMapper;

    @Autowired
    SysProvinceMapper sysProvinceMapper;
    @Autowired
    CustomerMapper customerMapper;

    @Autowired
    SysSalesPermissionMapper sysSalesPermissionMapper;

    @Autowired
    SysBankNumberMapper sysBankNumberMapper;

    @Autowired
    CacheService cacheService;

    @Autowired
    ApprovalCompletedMapper approvalCompletedMapper;

    @Reference
    LocationInfoFacade locationInfoFacade;

    @Autowired
    SysCreditLevelItemMapper sysCreditLevelItemMapper;
    
    @Autowired
    SysCreditLevelResultMapper sysCreditLevelResultMapper;

    /**
     * 文件名缓存
     */
    public static Map<String, String> fileNameCache = new HashMap<>();

    public PageWrap<BankNumberResp> getBankNumber(BankNumberReq req) {
        Page<Object> page = PageHelper.startPage(req.getPageNum(), req.getPageSize());
        List<SysBankNumber> sysBankNumberList = sysBankNumberMapper.selectLikeByBankName(req.getBankName());
        List<BankNumberResp> respList = BeanUtils.convertList(BankNumberResp.class, sysBankNumberList);
        PageWrap<BankNumberResp> pageWrap = new PageWrap<>();
        pageWrap.setValue(page);
        pageWrap.setResult(respList);
        return pageWrap;
    }

    /**
     * 获取客户名称
     *
     * @param customerName
     * @return
     */
    public List<String> getCustomerNames(String customerName) {
        return customerMapper.selectLikeByCustomerName(customerName);
    }

    /**
     * 获取销售业务员
     *
     * @param phoneOrName
     * @return
     */
    public List<SysSalesPermission> getSalesUser(String phoneOrName) {
        List<String> positions = new ArrayList<>();
        positions.add(PositionEnum.AREA_MANAGER.toString());
        positions.add(PositionEnum.SALES_MANAGER.toString());
        positions.add(PositionEnum.SALES.toString());
        List<SysSalesPermission> sysSalesPermissions = sysSalesPermissionMapper.selectByPhoneOrNameAndPositions(
                positions, phoneOrName);
        return sysSalesPermissions;
    }

    /**
     * 获取客户分类
     *
     * @return
     */
    public List<CategoryTree> getCustomerCategory() {
        List<CategoryTree> categoryTreeList = new ArrayList<>();
        List<SysCustomerCategory> sysCustomerCategoryList = sysCustomerCategoryMapper.selectAllList();

        sysCustomerCategoryList.forEach(sysCustomerCategory -> {
            if (sysCustomerCategory.getLevel().equals(1)) {
                CategoryTree categoryTree = BeanUtils.convert(CategoryTree.class, sysCustomerCategory);
                categoryTree.setCode(sysCustomerCategory.getCategoryCode());
                categoryTree.setName(sysCustomerCategory.getCategoryName());
                categoryTreeList.add(categoryTree);
            }
        });
        this.forE(categoryTreeList, sysCustomerCategoryList);
        return categoryTreeList;
    }

    private void forE(List<CategoryTree> categoryTreeList, List<SysCustomerCategory> sysCustomerCategoryList) {
        categoryTreeList.forEach(categoryTree -> {
            List<CategoryTree> subsetList = new ArrayList<>();
            sysCustomerCategoryList.forEach(sysCustomerCategory -> {
                if (sysCustomerCategory.getParentCode().equals(categoryTree.getCode())) {
                    CategoryTree subCategoryTree = BeanUtils.convert(CategoryTree.class, sysCustomerCategory);
                    subCategoryTree.setCode(sysCustomerCategory.getCategoryCode());
                    subCategoryTree.setName(sysCustomerCategory.getCategoryName());
                    subsetList.add(subCategoryTree);
                }
            });
            categoryTree.setSubsets(subsetList);
            this.forE(subsetList, sysCustomerCategoryList);
        });
    }

    /**
     * 获取行政区划
     *
     * @return
     */
    public List<RegionTree> getRegion() {
        List<RegionTree> regionTreeList = new ArrayList<>();

        List<SysRegion> sysRegionList = sysRegionMapper.selectAllList();
        for (SysRegion sysRegion : sysRegionList) {
            if (sysRegion.getRegionLevel().intValue() == 1) {
                RegionTree regionTree = new RegionTree();
                regionTree.setId(sysRegion.getId());
                regionTree.setRegionCode(sysRegion.getRegionCode());
                regionTree.setSapCode(sysRegion.getSapCode());
                regionTree.setRegionName(sysRegion.getRegionName());
                regionTree.setLevel(sysRegion.getRegionLevel());
                regionTreeList.add(regionTree);
            }
        }

        for (RegionTree regionTree : regionTreeList) {
            List<RegionTree> subsetList = new ArrayList<>();
            for (SysRegion sysRegion : sysRegionList) {
                if (sysRegion.getRegionLevel().intValue() == 2 && regionTree.getRegionCode().equals(sysRegion.getParentCode())) {
                    RegionTree regionTree2 = new RegionTree();
                    regionTree2.setId(sysRegion.getId());
                    regionTree2.setRegionCode(sysRegion.getRegionCode());
                    regionTree2.setSapCode(sysRegion.getSapCode());
                    regionTree2.setRegionName(sysRegion.getRegionName());
                    regionTree2.setLevel(sysRegion.getRegionLevel());
                    subsetList.add(regionTree2);
                }
            }
            regionTree.setSubsets(subsetList);
        }

        for (RegionTree regionTree : regionTreeList) {
            List<RegionTree> regionTree2List = regionTree.getSubsets();
            for (RegionTree regionTree2 : regionTree2List) {
                List<RegionTree> subsetList = new ArrayList<>();
                for (SysRegion sysRegion : sysRegionList) {
                    if (sysRegion.getRegionLevel().intValue() == 3 && regionTree2.getRegionCode().equals(sysRegion.getParentCode())) {
                        RegionTree regionTree3 = new RegionTree();
                        regionTree3.setId(sysRegion.getId());
                        regionTree3.setRegionCode(sysRegion.getRegionCode());
                        regionTree3.setSapCode(sysRegion.getSapCode());
                        regionTree3.setRegionName(sysRegion.getRegionName());
                        regionTree3.setLevel(sysRegion.getRegionLevel());
                        subsetList.add(regionTree3);
                    }
                }
                regionTree2.setSubsets(subsetList);
            }
        }

        return regionTreeList;
    }

    /**
     * 获取销售省区
     *
     * @return
     */
    public List<SalesProvinceAreaResp> getSysProvince() {
        List<SysProvince> sysProvinceList = sysProvinceMapper.selectAllList();
        return BeanUtils.convertList(SalesProvinceAreaResp.class, sysProvinceList);
    }

    /**
     * 根据省区编码获取销售省区
     * @param code
     * @return
     */
    public SysProvince getSysProvince(String code) {
        return sysProvinceMapper.selectByProvinceCode(code);
    }

    /**
     * 获取公司代码
     *
     * @return
     */
    public List<CompanyCodeResp> getCompanyCode() {
        List<SysCompanyCode> sysCompanyCodeList = sysCompanyCodeMapper.selectAllList();
        return BeanUtils.convertList(CompanyCodeResp.class, sysCompanyCodeList);
    }

    @Value("${hotfile.upload.url}")
    private String uploadFileUrl;
    @Value("${hotfile.login-token}")
    private String loginToken;

    /**
     * 上传文件
     * @param file
     * @return
     */
    public UploadFile uploadFiles(MultipartFile file) {
        String filename = file.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf(".") + 1);
        if (!UploadFileSuffixEnum.valid(suffix)) {
            throw new BusinessException("不支持的文件格式");
        }
        String fileUrl = HotFileUtils.uploadFile(uploadFileUrl, loginToken, file);
        return new UploadFile(fileUrl, filename);
    }

    /**
     * 获取信控等级维度项目
     * @param creditLevelDimensionEnum
     * @return
     */
    public List<CreditLevelItemResp> getCreditLevelItem(CreditLevelDimensionEnum creditLevelDimensionEnum) {
        List<SysCreditLevelItem> sysCreditLevelItems = sysCreditLevelItemMapper.selectByType(creditLevelDimensionEnum.toString());
        return BeanUtils.convertList(CreditLevelItemResp.class, sysCreditLevelItems);
    }

    /**
     * 计算客户级别
     * @param req
     * @return
     */
    public CreditLevelResultResp getCreditLevelResult(CreditLevelReq req) {
        Integer score = 0;
        SysCreditLevelItem archiveCategoryItem = sysCreditLevelItemMapper.selectByPrimaryKey(req.getArchiveCategoryId());
        SysCreditLevelItem customerNatureItem = sysCreditLevelItemMapper.selectByPrimaryKey(req.getCustomerNatureId());
        SysCreditLevelItem registeredCapitalItem = sysCreditLevelItemMapper.selectByPrimaryKey(req.getRegisteredCapitalId());
        if (archiveCategoryItem != null) {
            score = score + archiveCategoryItem.getScore();
        }
        if (customerNatureItem != null) {
            score = score + customerNatureItem.getScore();
        }
        if (registeredCapitalItem != null) {
            score = score + registeredCapitalItem.getScore();
        }
        SysCreditLevelResult sysCreditLevelResult = sysCreditLevelResultMapper.selectByScore(score);
        CreditLevelResultResp creditLevelResultResp = BeanUtils.convert(CreditLevelResultResp.class, sysCreditLevelResult);
        creditLevelResultResp.setRiskExplain("评分" + score + "分," + creditLevelResultResp.getRiskExplain());
        return creditLevelResultResp;
    }


    /**
     * 获取门店信息
     *
     * @return
     */
    public List<ShopLocationResp> getShopLocationList() {
        CommonResultResponse<List<ResSimpleLocationInfoVO>> response = locationInfoFacade.getLocationSimpleInfoList();
        if (response.getCode() != ResponseCode.SUCCESS) {
            throw new BusinessException("获取门店信息失败");
        }
        return BeanUtils.convertList(ShopLocationResp.class, response.getResult());
    }

    public boolean checkUserExist(Long userId) {
        Long id = sysSalesPermissionMapper.checkUserExist(userId);
        if (null == id) {
            return false;
        } else {
            return true;
        }
    }

    public String getRejectReason(Long approvalId,String nodeCode){
        String rejectReason ="";
        ApprovalCompleted approvalCompleted = approvalCompletedMapper.selectByApprovalIdAndNode(approvalId,nodeCode);
        if (null!=approvalCompleted){
            rejectReason = approvalCompleted.getRejectReason();
        }

        return rejectReason;
    }
}
